package com.yxq.mdt.app.modules.socialcontact.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.SoundPool;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.orhanobut.hawk.Hawk;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.base.BaseActivity;
import com.yxq.mdt.app.base.CustomClickListener;
import com.yxq.mdt.app.base.ibase.IBaseContract;
import com.yxq.mdt.app.constant.SPKey;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.splash.ui.SplashActivity;

/**
 * @author L
 * @time 2019-12-26
 * @describe $
 */
public abstract class CallActivity<P extends IBaseContract.IBasePresenter> extends BaseActivity<P> {

    protected AudioManager audioManager;
    protected Ringtone ringtone;
    protected SoundPool soundPool;
    protected int outgoing;
    private RxPermissions rxPermissions;
    public static String[] permissions = {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO};
    private CostumerDialog mPermissionDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);//获取当前通话最大音量
        audioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, maxVolume, AudioManager.USE_DEFAULT_STREAM_TYPE);
    }

    @Override
    public int getLayoutId() {
        return 0;
    }

    @Override
    public void initView() {
        rxPermissions = new RxPermissions(this);
        handlePermissionLogic();
        //locationPermissionCheck();
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {


    }

    /**
     * 获取权限
     */
    private void locationPermissionCheck() {
        if (ContextCompat.checkSelfPermission(mActivity, Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(mActivity, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请相机，麦克风权限
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA}, 10086);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (soundPool != null)
            soundPool.release();
        if (ringtone != null && ringtone.isPlaying())
            ringtone.stop();
        audioManager.setMode(AudioManager.MODE_NORMAL);
        audioManager.setMicrophoneMute(false);
    }

    public boolean checkPermission3(Context context, String[] permissions) {

        for (String permission : permissions) {
            int per = ContextCompat.checkSelfPermission(context, permission);
            if (PackageManager.PERMISSION_GRANTED != per) {
                return false;
            }
        }
        return true;
    }

    @SuppressLint("CheckResult")
    private void handlePermissionLogic() {

        if (checkPermission3(CallActivity.this, permissions)) {
            //已经同意全部权限
        } else {
            requestPermissions();
        }
    }

    /**
     * 请求权限
     */
    @SuppressLint({"CheckResult", "AutoDispose"})
    private void requestPermissions() {
        rxPermissions.request(permissions).subscribe(permission -> {
            if (permission) {
                // 用户同意所有权限
            } else {
                showConfirmDialog("该功能需要使用手机摄像头权限和麦克风权限.", new CustomClickListener() {
                    @Override
                    public void onSingleClick() {
                        gotoPermissionManager();
                    }
                }, new CustomClickListener() {
                    @Override
                    public void onSingleClick() {
                        finish();
                    }
                });
            }
        });
    }

    /**
     * 显示对话框
     */
    public void showConfirmDialog(@NonNull String context, @NonNull View.OnClickListener sureListener, @NonNull View.OnClickListener cancelListener) {

        if (mPermissionDialog == null) {
            mPermissionDialog = new CostumerDialog.Builder(this, R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_confirm_cancel_layout)
                    .setCancelable(false)
                    .create();
        }

        TextView title = mPermissionDialog.findViewById(R.id.tv_title);
        title.setText("授权提示");

        TextView content = mPermissionDialog.findViewById(R.id.tv_content);
        content.setText(context);

        //确定
        TextView sure = mPermissionDialog.findViewById(R.id.tv_sure);
        sure.setOnClickListener(v -> {
            sureListener.onClick(v);
        });

        //取消
        TextView cancel = mPermissionDialog.findViewById(R.id.tv_cancel);
        cancel.setOnClickListener(v -> {
            mPermissionDialog.dismiss();
            cancelListener.onClick(v);
        });
        mPermissionDialog.show();
    }

    /**
     * play the incoming call ringtone
     */
    protected int playMakeCallSounds() {
        try {
            audioManager.setMode(AudioManager.MODE_RINGTONE);
            audioManager.setSpeakerphoneOn(true);

            // play
            int id = soundPool.play(outgoing, // sound resource
                    0.3f, // left volume
                    0.3f, // right volume
                    1,    // priority
                    -1,   // loop，0 is no loop，-1 is loop forever
                    1);   // playback rate (1.0 = normal playback, range 0.5 to 2.0)
            return id;
        } catch (Exception e) {
            return -1;
        }
    }

    protected void openSpeakerOn() {
        try {
            if (!audioManager.isSpeakerphoneOn())
                audioManager.setSpeakerphoneOn(true);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void closeSpeakerOn() {

        try {
            if (audioManager != null) {
//                int curVolume = audioManager.getStreamVolume(AudioManager.MODE_IN_COMMUNICATION);
                if (audioManager.isSpeakerphoneOn())
                    audioManager.setSpeakerphoneOn(false);
                audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
//                audioManager.setStreamVolume(AudioManager.MODE_IN_COMMUNICATION,
//                        curVolume, AudioManager.MODE_IN_COMMUNICATION);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        int max, current, volume;
//        max = audioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
//        volume = audioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);

        switch (keyCode) {
            case KeyEvent.KEYCODE_VOLUME_UP:
//                if (volume < max)
//                    volume++;
//
//                audioManager.setStreamVolume(
//                        AudioManager.MODE_IN_COMMUNICATION,
//                        volume,
//                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true;

            case KeyEvent.KEYCODE_VOLUME_DOWN:
//                if (volume > 0)
//                    volume--;
//
//                audioManager.setStreamVolume(
//                        AudioManager.MODE_IN_COMMUNICATION,
//                        volume,
//                        AudioManager.FLAG_PLAY_SOUND | AudioManager.FLAG_SHOW_UI);
                audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER,
                        AudioManager.FX_FOCUS_NAVIGATION_UP);
                return true;
            case KeyEvent.KEYCODE_BACK:

                return true;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);


    }

}
